<template>
   <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
   <div class="add">
      <div class="common-layout">
        <el-container>
          <el-main>
            <el-row>
              <el-col :span="24">
                <div class="grid-content ep-bg-purple">
                  <h4>基本信息</h4>
                  <el-form :inline="true" :model="salesReturn" :rules="rules" status-icon ref="formRef">
                    <el-form-item label="单据编号" prop="docCode">
                <el-input 
                    v-model="salesReturn.docCode"
                    style="width: 240px"
                    placeholder="请输入单据编号"
                    clearable
                    :disabled="true"
                    />
                        </el-form-item>
                    <!-- 客户 -->
                    <el-form-item label="客户" prop="cid">
                            <el-select
                              v-model="salesReturn.cid" 
                              placeholder="请选择客户"
                              style="width: 240px"
                              clearable
                              filterable
                            >
                              <el-option
                                v-for="customer in customerList"
                                :key="customer.id"
                                :label="`${customer.code} - ${customer.name}`"
                                :value="customer.id"
                              />
                            </el-select>
                          </el-form-item>

                    <!-- 报价日期 -->
                    <el-form-item label="单据日期" prop="docDate">
                      <el-date-picker
                        v-model="salesReturn.docDate"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                      />
                    </el-form-item>
                    <!-- 业务员 -->
                     <el-form-item label="业务员" prop="uid">
                            <el-select
                              v-model="salesReturn.uid" 
                              placeholder="请选择客户"
                              style="width: 240px"
                              clearable
                              filterable
                            >
                              <el-option
                                v-for="user in userList"
                                :key="user.id"
                                :label="user.name"
                                :value="user.id"
                              />
                            </el-select>
                          </el-form-item>

                    <!-- 部门 -->
                    <el-form-item label="部门" prop="did">
                      <el-select
                        v-model="salesReturn.did"
                        placeholder="请选择部门"
                        style="width: 240px;"
                        clearable
                      >
                        <el-option 
                          v-for="dept in deptList"
                          :key="dept.id"
                          :label="dept.name"
                          :value="dept.id"
                        />
                      </el-select>
                    </el-form-item>

                    <!-- 备注 -->
                    <el-form-item label="备注" prop="notes">
                      <el-input
                        v-model="salesReturn.notes"              
                        style="width: 240px;"
                        placeholder="请输入备注信息"
                        clearable                       
                      />
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </div>
    </div>
    <div>
      <div class="toolbar">
    <el-button type="primary">商品信息</el-button>
    <el-button @click="addGoodsRow">继续添加</el-button>
    <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
  </div>

  <!-- 商品信息表格 -->
  <el-table :data="tableData" border style="width: 100%" class="goods-table" @selection-change="newHHandleSelectionChange">
    <el-table-column type="selection" width="55"  :selectable="(row:any) => !row.isLocked" />
    <!-- 商品编码（带必填标识的下拉框） -->
    <el-table-column label="商品编码" width="150">
      <template #header>
        <span class="required-label">商品编码</span>
      </template>
      <template #default="scope">
        <el-select 
          v-model="scope.row.code" 
          placeholder="请选择商品"
          @change="handleGoodsChange(scope.row)"
          :disabled="scope.row.isLocked"
          clearable
        >
          <el-option
            v-for="item in goodsList"
            :key="item.code"
            :label="`${item.code} - ${item.name}`"
            :value="item.code"
          />
        </el-select>
      </template>
    </el-table-column>

    <!-- 商品名称 -->
    <el-table-column label="商品名称" width="180">
      <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
    </el-table-column>

    <!-- 仓库信息 -->
    <el-table-column label="仓库" width="120" align="center">
      <template #default="scope">{{ scope.row.storeName }}</template>
    </el-table-column>

    <!-- 即时库存 -->
    <!-- <el-table-column label="即时库存" width="100" align="center">
      <template #default="scope">{{ scope.row.stock || 0 }}</template>
    </el-table-column> -->

    <!-- 单位 -->
    <el-table-column label="单位" width="80" align="center">
      <template #header>
        <span class="required-label">单位</span>
      </template>
      <template #default="scope">{{ scope.row.unit || '件' }}</template>
    </el-table-column>

    <!-- 数量 -->
    <el-table-column label="数量" width="120" align="center">
      <template #header>
        <span class="required-label">数量</span>
      </template>
      <template #default="scope">
        <el-input-number 
          v-model="scope.row.quantity" 
          :min="1" 
           :disabled="scope.row.isLocked"
          :max="scope.row.stock"
          controls-position="right"
          style="width: 100px"
        >
      </el-input-number>
      </template>
    </el-table-column>

    <el-table-column label="已出库数量" width="120" align="center">
      <template #default="scope">{{ scope.row.outStoreNum || 0 }}</template>
    </el-table-column>

    <el-table-column label="已出库总金额" width="120" align="center">
      <template #default="scope">{{ scope.row.outStoreSumCost || 0 }}</template>
    </el-table-column>

    <el-table-column label="退货数量" width="150" align="center">
      <template #header>
        <span class="required-label">退货数量</span>
      </template>
      <template #default="scope">
        <el-input-number 
          v-model="scope.row.returnQuantity"
          :min="0"
          :max="scope.row.outStoreNum"
          :precision="0"
          controls-position="right"
          style="width: 120px"
        />
      </template>
    </el-table-column>




    <!-- 实际报价（可输入） -->
    <el-table-column label="实际报价" width="130" align="center">
      <template #default="scope">
        <el-input 
          v-model.number="scope.row.actualPrice" 
           :disabled="scope.row.isLocked"
          placeholder="输入报价"
          @input="validatePrice(scope.row)"
        >
          <template #append>元</template>
        </el-input>
      </template>
    </el-table-column>
        <!-- 退货原因 -->
        <el-table-column label="退货原因" width="200" align="center">
      <template #default="scope">
        <el-input 
          v-model="scope.row.returnReason" 
          placeholder="请输入退货原因"
          clearable
        />
      </template>
    </el-table-column>

    <!-- 其他只读列 -->
    <el-table-column 
      v-for="col in readonlyColumns"
      :key="col.prop"
      :prop="col.prop"
      :label="col.label"
      :width="col.width"
      align="center"
    />
  </el-table>
 
     </div>
     <div class="total-summary">
      <div class="total-label">合计</div>
      <div class="total-amount">{{ formatTotal }}</div>
    </div>

  <el-dialog
  v-model="dialogVisible"
  title="销售出库单"
  width="80%"
  top="5vh"
>
  <!-- 查询条件区域 -->
  <div class="dialog-header">
    <el-input 
      v-model="searchForm.code" 
      placeholder="请输入单据编号" 
      style="width: 240px;margin-right: 15px"
    />
    <span class="date-label">单据日期：</span>
    <el-date-picker
      v-model="searchForm.startDate"
      type="date"
      placeholder="开始日期"
      value-format="YYYY-MM-DD"
      style="width: 160px"
    />
    <span class="date-separator">~</span>
    <el-date-picker
      v-model="searchForm.endDate"
      type="date"
      placeholder="结束日期"
      value-format="YYYY-MM-DD"
      style="width: 160px;margin-right: 15px"
    />
    <el-button type="primary" icon="Search" @click="searchSalesOut">查询</el-button>
    <el-button icon="Refresh" @click="resetSearch">重置</el-button>
    <el-button icon="ArrowDown">展开</el-button>
  </div>

  <!-- 选择状态提示 -->
  <div class="selected-info">
    <span>已选择{{ selectedCount }}项</span>
    <el-button link type="primary" @click="clearSelection">清空</el-button>
  </div>

  <!-- 表格区域 -->
  <el-table 
    :data="salesOutList" 
    border 
    height="60vh"
    @selection-change="handleSelectionChange"
    
  >
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column prop="code" label="单据编号" width="180" />
    <el-table-column prop="orderDate" label="单据日期" width="120" />
    <el-table-column prop="bjName" label="单据主题" width="200" />
    <el-table-column prop="customerName" label="客户" width="120" />
    <el-table-column prop="deptName" label="业务部门" width="120" />
    <el-table-column prop="storeManName" label="业务员" width="120" />
    <el-table-column prop="closed" label="已关闭" width="100" align="center">
      <template #default="scope">
        <el-tag :type="scope.row.closed ? 'danger' : 'success'" size="small">
          {{ scope.row.closed ? '是' : '否' }}
        </el-tag>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页及操作按钮 -->
  <div class="dialog-footer">
     <!-- 分页组件 -->
     <div class="pagination-wrapper">
            <el-pagination
                background
                layout="prev, pager, next"
                :total="totalItems"
                :page-size="PopupsPageSize"
                :current-page="PopupsPageNo"
                @current-change="handlePageChange"
            />
        </div>
    <div class="action-buttons">
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="confirmSelection">确定</el-button>
    </div>
  </div>
</el-dialog>



</template>


<script setup lang="ts">
import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
import type {FunctionalComponent} from 'vue'
import type {Column, InputInstance} from 'element-plus'
import { useRouter,useRoute } from 'vue-router';
import type { Goods } from '@/types/public-xs/Goods';  
import type { SalesOut,SalesOutDetail,SalesReturn,SalesReturnDetail } from '@/types/public-xs/salesDocuments';
import type { Customer } from '@/types/public-xs/Customer';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus'
 import type { User,Department } from '@/types/rs/User';
import request from '@/util/request';



//销售订单
let docCode=ref('')
//报价源单
let sourceSheet=ref('')
let title=ref('销售退货单')
let goodsList=ref<Goods[]>([])
let pageNo=ref(1)
let pageSize=ref(5)
let allPage=ref(0)
let router=useRouter()
//部门情况

//商品查询条件
const queryConditions = reactive({
  combine: '',
  kid: ''
})
const rules = reactive<FormRules>({
  cid: [{
    required: true, 
    message: '必须选择客户', 
    trigger: ['blur', 'change'],
    type: 'number'
  }],
  docDate: [
  { 
    required: true, 
    message: '必须选择单据日期', 
    trigger: 'change',
    validator: (_, value) => {
      if (!value) return false
      
      // 创建只包含日期的对象（忽略时间）
      const selected = new Date(value)
      const selectedDateOnly = new Date(
        selected.getFullYear(),
        selected.getMonth(),
        selected.getDate()
      )
      
      const today = new Date()
      const todayDateOnly = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate()
      )
      
      return selectedDateOnly > todayDateOnly 
        ? '不能选择未来日期' 
        : true
    }
  }
],
  uid: [{
    required: true,
    message: '必须选择业务员',
    trigger: ['blur', 'change'],
    validator: (_, value, callback) => {
      if (!value || !userList.value.some(u => u.id === value)) {
        callback(new Error('无效的业务员'))
      }
      callback()
    }
  }]
})
const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
}
// 修改handleAction方法
const handleAction = (action:string) => {
  switch(action) {
    case 'choose':
      if (!salesReturn.value.cid) {
        ElMessage.warning('请先选择客户')
        return
      }
      dialogVisible.value = true
       // 自动触发数据加载
       searchSalesOut()
      break
    case 'save-add':
      insertSalesOrder()
      break;
    case 'history':
      router.push('/home/salesReturnInfo')
      break;
  }
}
async function fetchData(page: number) {
  try {
    const params = new URLSearchParams();
    params.append('pageNow', page.toString());
    params.append('pageSize', pageSize.value.toString());
    params.append('combine', queryConditions.combine);
    params.append('kid', queryConditions.kid);

    let response = await request.post('/basic/good/getAll', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    goodsList.value = response.data.data.map((item: any) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      unique: item.unique,
      tax: item.tax,
      stock: item.stock,
      kname: item.kname
    }));
    console.log("拿到的商品集合",goodsList.value)
    allPage.value = response.data.data.total || 0;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    tableData.value = [];
    allPage.value = 0;
    console.error('获取数据失败:', error);
  }
}
fetchData(1)  
const mainActions = ref([
  {
    name: 'save-add',
    label: '保存新增',
    disabled: false
  },
  {
    name: 'choose',
    label: '选择源单',
    hidden: false
  },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }
])
let salesReturn=ref<SalesReturn>({
    id:0,
    docCode:docCode.value,
    docDate:new Date,
    cid: null,
    uid: 1,
    did:1,
    status: 0,
    totalReturnAmount: 0,
    actualReturnAmount: 0,
    remainAccount: 0,
    notes: '',
    createBy: '毕建峰',
    createTime: new Date,
    updateBy: '毕建峰',
    updateTime: new Date,
    isDelete: 0,
    customerAddress:'红盾小区',
    sourceSheet:sourceSheet.value,
    typeId:3
})


//访问方法并获取单据编号
let getDocCode=async()=>{
  let response=await request.post('/xs/counter/addCode',{docType:'XSTHD'})
  docCode.value=response.data.data
  salesReturn.value.docCode=docCode.value
}

onMounted(async () => {
  await getDocCode()
})

// todo
const generateUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
//动态加载客户
let customerList = ref<Customer[]>([])
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectAllCustomer')
    customerList.value = response.data.data
    console.log(customerList.value)

}
selectCustomer()

//查询业务员的方法
let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await request.post('/per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()

const tableData = ref([{ 
  id: generateUUID(), 
  goodId:0,
  code: '',
  name:'',
  quantity: 1,
  actualPrice: 0,
  returnReason: '',
  tax: 13,
  taxIncludedPrice: 0,
  stock:100,
  unit: '',
  kname:'',
  returnQuantity:0,
  storeName:'',
  outStoreSumCost:0,
  outStoreNum:0
  
}])

//选中商品数据
const handleGoodsChange = (row:any) => {
  const selected = goodsList.value.find(item =>item.code === row.code)
   console.log("选中的数据", selected)
  if (selected) {
    row.goodsName = selected.name
    row.code=selected.code
    row.goodId = selected.id; 
    row.stock = selected.stock;
    row.unit = selected.unique
    row.tax = selected.tax;
    row.kname = selected.kname  
    row.stock=Math.max(1, selected.stock || 1) 
    calculateTaxPrice(row)
  } else {
    // 清空相关字段
    row.goodsName = ''
    row.unit = '件'
    row.stock = 0
    row.stock = 1
  }
}
const newSelectedRows = ref<any[]>([])

// 处理选中行变化
const newHHandleSelectionChange = (selection: any[]) => {
  newSelectedRows.value = selection
}

// 删除选中行方法（添加确认对话框）
const deleteSelectedRows = async () => {
  if (newSelectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // 通过ID过滤实现删除
    const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
    tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.info('已取消删除')
  }
}


//价格校验
const validatePrice = (row:any) => {
  row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
}

// 含税价计算
const calculateTaxPrice = (row:any) => {
  if (row.actualPrice && row.vatRate) {
    row.taxIncludedPrice = (row.actualPrice * (1 + row.vatRate/100)).toFixed(2)
  }
}

//只读队列
const readonlyColumns = [
  { prop: 'kname', label: '商品种类', width: 120 },
  { prop: 'tax', label: '增值税税率 (%)', width: 150 }
]
// 显示历史报价
const showHistory = (row:any) => {
  console.log('显示历史报价:', row.code)
  // 实际应调用API获取历史数据
}
//格式化金额显示
const totalAmount = computed(() => {
  return tableData.value.reduce((sum, row) => {
    const price = Number(row.actualPrice) || 0
    const qty = Number(row.returnQuantity) || 0 // 关键修改点
    return sum + (price * qty)
  }, 0)
})
const formatTotal = computed(() => {
  return `¥${totalAmount.value.toFixed(2)}`
})
let PopupsPageNo=ref(1)
let PopupsPageSize=ref(8) 
const selectedCount = ref(0)
const totalItems = ref(0)
const dialogVisible = ref(false)
const currentSelected =ref<SalesOut|null>()
const selectedRows =ref<SalesOut[]>([])
const searchForm = reactive({
  code: '',
  startDate: '',
  endDate: ''
})
// 表格选择处理
const handleSelectionChange = (selection:any) => {
  selectedRows.value = selection
  selectedCount.value = selection.length
  if (selection.length > 0) {
    currentSelected.value = selection[0]
  } else {
    currentSelected.value = null
  }
}
const clearSelection = () => {

}

//分页方法
let handlePageChange=(newPage:number)=>{
   PopupsPageNo.value = newPage;
  searchSalesOut();

}
let salesOutList=ref<SalesOut[]>([])
// 分页查询方法
const searchSalesOut = async () => {
  try {
    const params = {
      code: searchForm.code,
      startDate: searchForm.startDate,
      endDate: searchForm.endDate,
      pageNo: PopupsPageNo.value,
      pageSize: PopupsPageSize.value,
      cid:salesReturn.value.cid,
      typeId:6
    }
    const res = await request.post('/kc/outStore/getOutStoreList', params)
    salesOutList.value = res.data.data.list
    console.log("出库单的数据",salesOutList.value)
    totalItems.value = res.data.data.total
  } catch (error) {
    console.error('查询失败:', error)
  }
}
const resetSearch = () => {
  searchForm.code = ''
  searchForm.startDate = ''
  searchForm.endDate = ''
  searchSalesOut()
}

const confirmSelection = async() => {
  if (currentSelected.value) {
    sourceSheet.value = currentSelected.value.code
    ElMessage.success(`已选择源单：${currentSelected.value.code}`)
    salesReturn.value.sourceSheet=sourceSheet.value
    //获取到源单相应的明细数据
    try{
    const detailRes =  await request({
    method:'post',
    url:'/kc/outStoreDetail/getOutStoreDetailList',
    data:{
      outStoreCode:sourceSheet.value
    },
    headers:{
      'Content-Type':'application/x-www-form-urlencoded'
    }
  })
    console.log("获取到的源单数据",detailRes.data.data)
    const goodIds = detailRes.data.data
      .map((item: any) => item.goodId)
      .filter((id: number) => id > 0);
    // 4. 批量查询商品信息
    console.log("商品id数组",goodIds)
    const goodsRes = await request.post('/basic/good/getGoodList', goodIds );
    // 5. 创建商品映射表
    const goodsMap = new Map();
    goodsRes.data.data.forEach((good: Goods) => {
      goodsMap.set(good.id, good);
    });
    // 6. 合并数据到表格
    tableData.value = detailRes.data.data.map((item: any) => {
      const good = goodsMap.get(item.goodId) || {};
      console.log(good)
      return {
        code: good.code || '未知编码',
        goodsName: good.name || '未知商品',
        outStoreNum: item.count,//出库数量
        actualPrice: item.outStoreSingleCost,
        kname: item.kname || '件',
        stock: good.stock || 1000,
        goodId: item.goodId, // 保留原始ID用于后续操作
        tax: item.tax || good.tax, 
        returnQuantity:Math.min(item.count, 0),
        storeName:item.storeName,
        outStoreSumCost:item.outStoreSumCost,
        returnReason:item.item,
        unit: good.uname || '件',
         isLocked: true,
      };
    });
    await selectCustomer()
    await fetchData(1)
  }catch{
    ElMessage.error('数据加载失败')
  }finally{
    dialogVisible.value = false
  }
  }
}
const generateDetails = () => {
  return tableData.value.map(item => ({
   id:0,
   xsReturnCode:salesReturn.value.docCode,
   goodId:item.goodId,
   quantity:item.quantity,
   discountRate:0,
   notes:'测试阶段',
   createBy:'毕建峰',
   createTime:new Date,
   updateBy:'毕建峰',
   isDelete:0,
   warehouseId:1,
   shippedQuantity:0,
   returnReason:item.returnReason,//退货原因
   returnQuantity:item.returnQuantity,//退货数量
   returnStatus:0,
   actualPrice: item.actualPrice 
  }))  as SalesReturnDetail[]
}

let addGoodsRow = () => {
  tableData.value.push({
    id:generateUUID(),
    goodId:0,
    code: '',  
    name:'',     // 商品编码（必填）
    quantity: 1,        // 数量（必填，默认1）
    actualPrice: 0,  // 实际报价
    returnReason: '',
    tax: 13,        // 增值税率
    taxIncludedPrice: 0,  // 含税单价
    stock:100,
    unit: '件',
    kname:'测试',
    returnQuantity:0,
    storeName:'',
    outStoreSumCost:0,
    outStoreNum:0
  })
}                        

const validateGoodsRows = () => {
  let isValid = true
  const errors: string[] = []
  console.log("表格数据",tableData.value)
  tableData.value.forEach((row, index) => {
    const rowNumber = index + 1
    if (!row.code) {
      errors.push(`第${rowNumber}行：必须选择商品编码`)
      isValid = false
    }
    if (row.returnQuantity <= 0) {
      errors.push(`第${rowNumber}行：退货数量必须大于0`)
      isValid = false
    }
    if (row.returnQuantity > row.outStoreNum) {
      errors.push(`第${rowNumber}行：退货数量不能超过已出库数量${row.outStoreNum}`)
      isValid = false
    }
    if (row.actualPrice <= 0) {
      errors.push(`第${rowNumber}行：实际报价必须大于0`)
      isValid = false
    }
  })

  if (!isValid) {
    ElMessage.error({
      message: `商品信息不完整：\n${errors.join('\n')}`,
      duration: 5000,
      customClass: 'error-message-box' 
    })
  }
  return isValid
}



const formRef = ref<FormInstance>()
//点击新增后新增销售退货单
const insertSalesOrder = async () => {
  try {
    // 1. 基础表单校验
    const formEl = formRef.value
    if (!formEl) return
    await formEl.validate() 
    // 2. 商品信息校验
    if (tableData.value.length === 0) {
      ElMessage.warning('至少需要添加一个退货商品')
      return
    }
    if (!validateGoodsRows()) return
  
    

    // 4. 执行提交
    salesReturn.value.totalReturnAmount = totalAmount.value
    const details = generateDetails()
    const res = await request.post('/xs/SalesReturnController/insertSalesReturn', {
      salesReturn: salesReturn.value,
      details: details
    })
    
    if (res.data.code == 200) {
      ElMessage.success({ message: '提交成功', duration: 1500 })
      router.push('/home/salesReturnInfo')
    }
  } catch (error) {
    console.error('表单验证失败', error)
    ElMessage.error('提交数据不完整，请检查红色提示项')
  }
}


</script>


<style scoped>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}
.pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}
.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.date-label {
  color: #606266;
  margin: 0 10px;
}

.date-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

.selected-info {
  margin: 12px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.pagination-info {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
}
/* 错误状态样式 */
:deep(.el-form-item.is-error) {
  .el-input__inner, .el-select__wrapper {
    box-shadow: 0 0 3px rgba(245,108,108,.3);
  }
}

/* 表格错误行高亮 */
.el-table__row.error-row {
  td {
    background-color: #fff3f3 !important;
    .cell { 
      color: #f56c6c;
      font-weight: 500;
    }
  }
}
</style>